<?php
namespace Common\Model;
use Think\Model;

class TokenModel extends Model
{
    /**
     * 登陆存token
     * @param $user 用户信息
     * @param int $type     //类型 1:后台客户 2:客户,员工
     * @param int $form     //平台类型，1就是默认，2:小程序 3:app
     * @return array
     */
    public function setToken($userInfo, $form=1, $type=1){
        $result = array(
            'status' => false,
            'data' => '',
            'msg' => ''
        );
        if($type==1){
		    $uid = $userInfo['aId'];
        }else{
            $uid = $userInfo['uid'];
        }
		$token = $this->algorithm($userInfo, $type);
        C('USER_CHECK_MODEL','db');
        if(strtolower(C('USER_CHECK_MODEL'))=='redis'){
            //ID加密
            $e_uid = authcode($userInfo['uid'], 'ENCODE');
            $redis = new \Redis();
            $config = C('APP_TOKEN_CONFIG');
            $redis->connect($config['host'], $config['port']);
            $redis->auth($config['password']);
            $re = $redis->setex('WToken_'.$uid,86400*30,$e_uid);//30天有效期
        }else if(strtolower(C('USER_CHECK_MODEL'))=='db'){
            $wdata['aId'] = $uid;
            $wdata['form'] = $form;
            $wdata['type'] = $type;
            $count = $this->where($wdata)->count();
            if($count>0){
                $sdata['edit_time'] = NOW_TIME;
                $sdata['token'] = $token;
                $re = $this->where($wdata)->save($sdata);
            }else{
                $data = $wdata;
                $data['edit_time'] = NOW_TIME;
                $data['token'] = $token;
                $re = $this->add($data);
            }
        }
		if($re!=false){
			$result['data'] = $token;
			$result['status'] = true;
			return $result;
		}else{
			$result['msg'] = "生成token失败";
			return $result;
		}

    }
    //二级密码验证token
    public function setTokencc($userInfo, $form=1, $type=1){
        $result = array(
            'status' => false,
            'data' => '',
            'msg' => ''
        );
        $uid = $userInfo['uid'];
		$token = $this->algorithm($userInfo, $type);
        $wdata['uids'] = $uid;
        $wdata['form'] = $form;
        $count =M('user_token')->where($wdata)->count();
        if($count>0){
            $sdata['edit_time'] = NOW_TIME;
            $sdata['token'] = $token;
            $re = M('user_token')->where($wdata)->save($sdata);
        }else{
            $data = $wdata;
            $data['edit_time'] = NOW_TIME;
            $data['token'] = $token;
            $re = M('user_token')->add($data);
        }
		if($re!=false){
			$result['data'] = $token;
			$result['status'] = true;
			return $result;
		}else{
			$result['msg'] = "生成token失败";
			return $result;
		}

    }


    public function delToken($token){
        $result = array(
            'status' => false,
            'data' => '',
            'msg' => ''
        );
        //删除掉旧的token
        //$where[] = ['user_id', 'eq', $user_id];
        $where[] = ['token', 'eq', $token];
        if($this->where($where)->delete()){
            $result['msg'] = '退出成功';
            $result['status'] = true;
        }else{
            $result['msg'] = '出错';
        }
        return $result;
    }
    public function delTokencc($token){
        $result = array(
            'status' => false,
            'data' => '',
            'msg' => ''
        );
        $where[] = ['token', 'eq', $token];
        if(M('user_token')->where($where)->delete()){
            $result['msg'] = '退出成功';
            $result['status'] = true;
        }else{
            $result['msg'] = '出错';
        }
        return $result;
    }


    /**
     * 根据token来获取用户的id
     * @param $token //token的值
     * @param int $status //用户状态，0是所有状态，1是取正常的用户状态
     * @return array|mixed
     */
    public function checkToken($token){
        $result = [
            'status' => false,
            'data' => '',
            'msg' => ''
        ];
        if(!$token){
			$this->error = 'Token必须';
            return false;
        }

        $wdata['token'] = $token;
        $wdata['edit_time'] = array('gt',NOW_TIME-60*60*24*180);//有效期180天
        $tokenInfo = $this->where($wdata)->find();
        if($tokenInfo){
			//$userInfo = get_user_base($tokenInfo['uid']);
            if($tokenInfo['type']==1){
                $a_model = M('Admin');
                $a_wdata['aId'] = $tokenInfo['aId'];
                $userInfo = $a_model->where($a_wdata)->find();
                if(!$userInfo){
                    $this->error = '用户不存在';
                    return false;
                }
                $userInfo['name'] = $userInfo['aName'];
            }else if($tokenInfo['type']==2){
                $a_model = M('User');
                $a_wdata['uid'] = $tokenInfo['aId'];
                $userInfo = $a_model->where($a_wdata)->find();
                if(!$userInfo){
                    $this->error = '用户不存在';
                    return false;
                }
                $userInfo['name'] = $userInfo['names'];
            }
            $userInfo['login_type'] = $tokenInfo['type'];
            $result['status'] = true;
            $result['data'] = $userInfo;
            return $result;
        }else{
            $result['msg'] = "不是有效的token";
            return $result;
        }
    }

	//刷新token (内部使用)
	public function refreshToken($token, $userInfo, $form=1){
		$this->checkToken($token);
		$token = $this->algorithm($userInfo);
		$uid = $userInfo['uid'];
		$data['uid'] = $uid;
		$data['form'] = $form;
		$count = $this->where($data)->count();
		if($count>0){
			$data['edit_time'] = NOW_TIME;
			$data['token'] = $token;
			$re = $this->save($data);
		}else{
			$data['edit_time'] = NOW_TIME;
			$data['token'] = $token;
			$re = $this->add($data);
		}
		if($re!==false){
			$result['data'] = $data['token'];
			$result['status'] = true;
			return $result;
		}else{
			$result['msg'] = "生成token失败";
			return $result;
		}		
	
	}

	//token组装规则
    function algorithm($userInfo, $type){
        if($type==1){
            $pre = 'a_';
        }else{
            $pre = 'c_';
        }
        if(strtolower(C('USER_CHECK_MODEL'))=='redis'){
			//redis加密方式
			$token = $pre.authcode($userInfo['uid'].'_'.microtime(true), 'ENCODE');
		}else{
			//H5、PC
			$token = $pre.md5($userInfo['uid'].'_'.microtime(true).'_'.$form);
		}
		//测试环境
		if($userInfo['uid']<102100){
			//$token = '9587fc2a4f1062deaafaf690b7195e7d_'.$userInfo['uid'];
		}
		return $token;

    }

}